package com.shut.vehicle.file;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import com.shut.vehicle.dao.ImageRecordDao;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
public class FileManagement {

    @Value("${file-dir}")
    private String fileBasePath;

    @Autowired
    private ImageRecordDao imageRecordDao;


    /**
     * 保存某次拍摄服务产生的所有图片信息
     *
     * @param filePath  某次服务的所有图片相对路径
     * @param userId    用户ID
     * @param serviceId 服务记录ID
     * @param deviceId  设备ID
     */
    public void saveFile(Set<String> filePath, Integer userId, Integer serviceId, Integer deviceId) {
        if (CollectionUtil.isEmpty(filePath)) {
            return;
        }
        filePath = filePath.stream().filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        imageRecordDao.saveImageRecord(userId, serviceId, deviceId, filePath);
    }


    /**
     * 某人某次服务产生的所有图片信息
     *
     * @param userId    用户ID
     * @param serviceId 服务记录ID
     * @return  相关所有图片
     */
    public Set<String> listFilePath(Integer userId, Integer serviceId) {
        return imageRecordDao.listImagePathInServiceRecord(userId, serviceId);
    }


    /**
     * 清理所有旧图片信息
     *
     * @param limitDateTime 截止时间
     */
    public void cleanOldImage(LocalDateTime limitDateTime) {
        Date date = Date.from(limitDateTime.atZone( ZoneId.systemDefault()).toInstant());
        Set<String> filePath = imageRecordDao.listImageBeforeTime(date);
        if (! filePath.isEmpty()) {
            for (String path : filePath) {
                String locationPath = (fileBasePath + path).replaceAll("//", "/");
                File file = new File(locationPath);
                file.deleteOnExit();
            }
        }
        imageRecordDao.deleteImageBeforeTime(date);
    }


}
